package com.lnj.community.controller;

import com.aliyun.oss.OSS;
import com.lnj.community.annotation.LoginRequired;
import com.lnj.community.config.OSSConfig;
import com.lnj.community.dao.entity.User;
import com.lnj.community.service.FollowService;
import com.lnj.community.service.LikeService;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.CommunityUtil;
import com.lnj.community.utiles.HostHolder;
import com.lnj.community.utiles.OSSUtile;
import com.lnj.community.utiles.RedisKeyUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import static com.lnj.community.utiles.CommunityConstant.ENTITY_TYPE_USER;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger log= LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Value("${server.servlet.context-path}")
    String contextPath ; // 注入项目名称
    @Value("${community.path.domain}")
    String domain ; // 注入域名
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private RedisTemplate redisTemplate;


    //上传头像 @LoginRequired 表示该方法需要登录才能访问
    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage() {
        return "/site/setting";
    }



    //修改密码
    @LoginRequired
    @RequestMapping(path = "/updatePassword", method = RequestMethod.POST)
    public String updatePassword(String oldPassword, String newPassword,String confirmPassword, Model model) {
        // 原密码
        User user = HostHolder.getUser();
        //判断原密码是否正确
        String password=userService.findPassword(user.getId());
        String s = CommunityUtil.md5(oldPassword + user.getSalt());
        if (!password.equals(s)) {
            model.addAttribute("oldPasswordMsg", "原密码不正确!");
            return "/site/setting";
        }
        if (StringUtils.isBlank(oldPassword)) {
            model.addAttribute("oldPasswordMsg", "原密码不能为空!");
            return "/site/setting";
        }
        if (StringUtils.isBlank(newPassword)) {
            model.addAttribute("newPasswordMsg", "新密码不正确!");
            return "/site/setting";
        }
        if (StringUtils.isBlank(confirmPassword)) {
            model.addAttribute("confirmPasswordMsg", "确认密码不正确!");
            return "/site/setting";
        }
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("confirmPasswordMsg", "两次输入的密码不一致!");
            return "/site/setting";
        }
        if (newPassword.equals(oldPassword)) {
            model.addAttribute("newPasswordMsg", "新密码不能与原密码相同!");
            return "/site/setting";
        }
        //修改密码
        userService.updatePassword(user.getId(), CommunityUtil.md5(newPassword + user.getSalt()));
        //修改成功 退出登录 重新登录
        model.addAttribute("msg", "修改密码成功,请重新登录!");
        return "redirect:/logout";

    }

    //修改头像
    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }
        //获取文件名称
        String fileName = headerImage.getOriginalFilename();
        //获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确!");
        }
        //生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        InputStream inputStream = null;
        String pickPath=null;
        try {
            inputStream = headerImage.getInputStream();
            pickPath = OSSUtile.uploadToAliyun(inputStream, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            }catch (Exception e){
                log.error("上传文件失败:"+e.getMessage());
                model.addAttribute("error", "上传文件失败!");
                throw new RuntimeException("上传文件失败,服务器发生异常",e);
            }
        }
        //更新当前用户的头像的路径(web访问路径)
        User user = HostHolder.getUser();
        //删除原来的头像
        String headerUrl = user.getHeaderUrl();
        OSSUtile.deleteFromAliyun(headerUrl);
        userService.updateHeadUrl(user.getId(),pickPath);
        HostHolder.setUser(userService.findUserById(user.getId()));
        model.addAttribute("loginUser", HostHolder.getUser());
        // 清除用户信息缓存
        String cacheKey = RedisKeyUtil.getUserKey(user.getId());
        redisTemplate.delete(cacheKey);
        return "redirect:/index";
    }

    //根据文件名,响应图片(在浏览器中展示图片)
    @LoginRequired
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //服务器存放路径
        fileName = "https://" + OSSConfig.BUCKET_NAME + "." + OSSConfig.ENDPOINT + "/" + fileName;
        //解析文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/" + suffix);
        try(
                FileInputStream fileInputStream = new FileInputStream(fileName);
            ) {
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, b);
            }
        }catch (Exception e){
            log.error("响应图片失败:"+e.getMessage());
            throw new RuntimeException("响应图片失败,服务器发生异常",e);
        }
    }

    //个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        //用户
        model.addAttribute("user", user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        //是否已关注
        boolean hasFollowed = false;
        if (HostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(HostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("followeeCount", followeeCount);
        model.addAttribute("followerCount", followerCount);
        model.addAttribute("hasFollowed", hasFollowed);
        System.out.println(likeCount);

        return "/site/profile";
    }

}
